<script setup lang="ts">
import { ref, computed, reactive } from 'vue';
import { useNurseStore, useAuthStore } from '@/store';
import { useNurseOrders, useDict } from '@/service';
import { hideLoading, showToast, showLoading, navigateBack, getCurrentInstance } from '@tarojs/taro';
import { localStg } from '@/utils';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { storeToRefs } from 'pinia';

const { imageUrl } = useNurseStore();

const { nurseUser } = storeToRefs(useAuthStore());

const {
    router: {
        params: { orderId }
    }
}: any = getCurrentInstance();

const { addComment } = useNurseOrders();

const { getDict } = useDict();

definePageConfig({
    navigationBarTitleText: '订单评价'
});
const comment = ref();

const rate: any = ref();

const formData = ref<any>({
    description: '',
    rate: undefined,
    evaluate: {},
    pics: {}
});

const ruleForm = ref<any>(null);

async function getData() {
    showLoading({ title: '正在请求数据...' });

    let result = await getDict('nurse_order_comment');

    if (result && result.length > 0) comment.value = result;

    result = await getDict('nurse_order_rate');

    if (result && result.length > 0) {
        const newArr = result.map((item: any) => {
            return {
                ...item,
                checked: false
            };
        });
        rate.value = newArr;
    }

    hideLoading();
}
getData();

function uploadDelete(data: any) {
    Reflect.deleteProperty(formData.value?.pics, `${data?.file?.name}`);
}

function uploadSuccess(data: any) {
    const result = JSON.parse(data?.data?.data);

    const fileItemName = data?.fileItem?.name;

    const { message, success } = result;

    if (success && message) {
        formData.value.pics[`${fileItemName}`] = message;
    }
}
const token = localStg.get('token');
const headers = ref({
    'Content-Type': 'multipart/form-data',
    'X-Access-Token': token
});
const defaultFileList = reactive<any>([]);

const rate_text = computed(() => rate.value?.find((item: any) => item?.itemValue == formData.value?.rate));

function clickEvaluate(item: any) {
    item.checked = !item.checked;
    if (item.checked) {
        formData.value.evaluate[`${item.itemText}`] = item.itemText;
    } else {
        Reflect.deleteProperty(formData.value?.evaluate, `${item.itemText}`);
    }
}

const submit = async () => {
    const { valid } = await ruleForm.value.validate();

    if (!valid) return;

    ruleForm.value.validate().then(async ({ valid }: any) => {
        if (!valid) return;

        showLoading({ title: '正在发布...' });

        const evaluate = Array.from(new Map(Object.entries(formData.value?.evaluate)))
            .map(([key, value]) => `${value}`)
            .join(',');

        const pic = Array.from(new Map(Object.entries(formData.value?.pics)))
            .map(([key, value]) => `${value}`)
            .join(',');

        const { error } = await addComment({
            ...formData.value,
            evaluate,
            orderId,
            pic,
            userId: nurseUser.value.id,
            status: '1'
        });
        if (!error) {
            hideLoading();
            showToast({
                title: '发布成功',
                icon: 'success',
                duration: SUCCESS_MSG_DURATION
            });
            setTimeout(() => {
                navigateBack();
            }, 1000);
        }
    });
};
</script>
<template>
    <basic-layout>
        <!-- <custom-navbar title="订单评价" showLeft /> -->
        <view class="w-375px flex-col-center">
            <nut-form ref="ruleForm" class="w-360px mb-50px" :model-value="formData">
                <nut-form-item class="flex-center" label="评论图片" prop="pic" :rules="[{ required: false, message: '' }]">
                    <nut-uploader v-model:file-list="defaultFileList" :headers="headers" :multiple="true"
                        :url="`${imageUrl}/sys/common/upload?biz=comment/${orderId}`" :maximize="1024 * 20000"
                        maximum="5" @success="uploadSuccess" @delete="uploadDelete"></nut-uploader>
                </nut-form-item>
                <nut-form-item label="评论" prop="description">
                    <!-- rows="3" :autosize="true" -->
                    <nut-textarea v-model="formData.description" placeholder="请输入评论" />
                </nut-form-item>
                <nut-form-item label="评分等级" prop="rate">
                    <view class="flex flex-center w-full h-20px">
                        <nut-rate v-model="formData.rate" class="w-2/3" size="24px" count="5" spacing="5" />
                        <view class="w-1/3 text-base text-primary">{{ rate_text?.itemText }}</view>
                    </view>
                </nut-form-item>
                <nut-form-item class="w-full" label="" label-width="0" prop="comment">
                    <nut-grid class="w-full" :column-num="3" :border="false" :gutter="0">
                        <nut-grid-item v-for="item in comment" class="flex-col-center h-40px"
                            @click="clickEvaluate(item)">
                            <nut-button plain size="mini" :type="item?.checked ? 'success' : 'default'">
                                {{ item.itemText }}
                            </nut-button>
                        </nut-grid-item>
                    </nut-grid>
                </nut-form-item>
            </nut-form>
            <view class="w-375px bg-white h-48px pos-fixed pos-bottom-10 pos-left-0 flex-center justify-around">
                <basic-button text="发布" @click="submit" />
            </view>
        </view>
    </basic-layout>
</template>
<style lang="scss">
.h5-img,
.h5-video {
    max-width: 100%;
    height: 100%;
}

.nut-grid-item__content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100%;
    padding: var(--nut-grid-item-content-padding, 0px 0px);
    background: var(--nut-grid-item-content-bg-color, var(--nut-white, #fff));
    border: 0 solid var(--nut-grid-border-color, #f5f6f7);
}
</style>
